﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SampleApp.MvcBackend.Runtime
{
	class PagingHelper
	{
		public class Results<T>
		{
			public IEnumerable<T> Items { get; set; }
			public Int32 TotalItemsCount { get; set; }
		}

		public static IEnumerable<TResult> GetAll<TResult>( Int32 pageSize, Func<Int32, Int32, Results<TResult>> pageGetter )
		{
			var result = new List<TResult>();
			var firstPage = pageGetter( 0, pageSize );
			result.AddRange( firstPage.Items );

			if ( firstPage.TotalItemsCount > pageSize )
			{
				Int32 rem;
				var pagesCount = Math.DivRem( firstPage.TotalItemsCount, pageSize, out rem );
				if ( rem > 0 )
				{
					pagesCount++;
				}

				for ( var i = 0; i < pagesCount; i++ )
				{
					var page = pageGetter( i + 1, pageSize );
					result.AddRange( page.Items );
				}
			}

			return result.AsReadOnly();
		}
	}
}
